#include <memory>
#include <vector>
#include <cstdio>
#include <string>
#include "server.hpp"

using namespace std; 
using namespace nt_server;

bool checkSafe(const string& comm)
{
    vector<string> unsafecomms{"kill", "mv", "while :; do", "shutdown"};

    for(auto &str : unsafecomms)
    {
        if(comm.find(str) != std::string::npos)
        {
            return false;
        }
    }
    return true;
}


string ExecCommand(const string& request)
{
    if(!checkSafe(request))
    {
        return "Non_safaety instruction, refuse to execute!";
    }
    
    FILE* fp = popen(request.c_str(), "r");
    if(fp == NULL)
    {
        return "Cant execute command!";
    }

    string ret;
    char buffline[1024];
    while(fgets(buffline, sizeof(buffline), fp) != NULL)
    {
        ret += buffline;
    }

    fclose(fp);

    return ret;

}

string UpToLow(const string& resquest)
{
    string ret(resquest);
    for(auto &rc : ret)
    {
        if(isupper(rc))
        {
            rc += 32;
        }
    }
    return ret;
}


int main()
{
    unique_ptr<UdpServer> usvr(new UdpServer(ExecCommand));
    usvr->InitServer();

    usvr->StartServer();

    return 0;
}
